package com.lmaye.design.patterns.creation.prototype.deepclone;

import java.io.*;

/**
 * -- Rabbit
 *
 * @author lmay.Zhou
 * @date 2020/11/18 23:46 星期三
 * @qq 379839355
 * @email lmay@lmaye.com
 * @since JDK1.8
 */
public class Rabbit implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * name
     */
    private String name;

    /**
     * Cat
     */
    private Cat friend;

    public Rabbit() {

    }

    public Rabbit(String name, Cat friend) {
        this.name = name;
        this.friend = friend;
    }

    /**
     * 深度拷贝
     * - 方式 1
     *
     * @return Object
     * @throws CloneNotSupportedException 异常
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        System.out.println("原型复制成功（深拷贝）");
        Rabbit cloneObj = (Rabbit) super.clone();
        cloneObj.friend = (Cat) friend.clone();
        return cloneObj;
    }

    /**
     * 深度拷贝
     * - 方式 2(推荐)
     *
     * @return Object
     * @throws Exception 异常
     */
    public Object clone2() throws Exception {
        // 序列化
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(this);
            // 反序列化
            try(ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis)) {
                return ois.readObject();
            }
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getFriend() {
        return friend;
    }

    public void setFriend(Cat friend) {
        this.friend = friend;
    }

    @Override
    public String toString() {
        return "Rabbit{" +
                "name='" + name + '\'' +
                ", friend=" + friend +
                '}';
    }
}
